#!/usr/bin/env python3

'''
Author       : bopo
Date         : 2020-12-08 10:09:56
LastEditors  : bopo
LastEditTime : 2020-12-08 14:10:35
FilePath     : /stealer/stealer/stealer.py
Description  :
'''
import importlib
import re

from .logger import log


class Stealer:
    mapper = {
        'kuaishou.com': ('stealer.adapter.kuaishou', 'KuaiShouAdapter'),
        'huoshan.com': ('stealer.adapter.huoshan', 'HuoShanAdapter'),
        'pipix.com': ('stealer.adapter.pipixia', 'PiPiXiaAdapter'),
        'douyin.com': ('stealer.adapter.douyin', 'DouYinAdapter'),
        'tiktok.com': ('stealer.adapter.tiktok', 'TikTokAdapter'),
        'ixigua.com': ('stealer.adapter.xigua', 'XiGuaAdapter'),
    }

    options = {

    }

    def __init__(self, options=None):
        self.options = options if options else self.options
        self.client = None
        self.index = None
        self.link = None

    def find_link(self, text: str):
        urls = re.findall(r'https?://[^\s]*', text, re.I | re.M)

        log.debug(urls)

        # if urls:
        #     return self.client.make_url(urls[0])

        return urls[0]

    def find_index(self, url):
        index = re.findall(r'(?<=com\/)\w+', url)
        log.debug(f'url=>{url}')
        log.debug(f'index=>{index}')

        try:
            return index[0]
        except IndexError:
            return None

    def fetch(self, output=None, stream=True):
        """
        获取视频地址
        :param output:
        :return:
        """
        log.warning(f'link: {self.link}')
        self.client.fetch(url=self.link, output=output, stream=stream)

    def dispatch(self, text=None):
        self.link = self.find_link(text)
        self.client = self.find_client(self.link)
        self.index = self.client.index(self.link)

        log.debug(f'client => {self.client.__class__}')

        return self

    def parse(self, header=True):
        """
        下载视频
        :return: dict
        """
        return self.client.parse(url=self.link, header=header)

    def find_client(self, link):
        log.debug(link)

        for x in self.mapper.keys():
            print(x)

            if x in link:
                log.debug(self.mapper.get(x))
                module = importlib.import_module(self.mapper.get(x)[0])
                return getattr(module, self.mapper.get(x)[1])(self.options)
        else:
            print(f'无法加载适配器 {link}')
            exit(1)


if __name__ == '__main__':
    # 下载文件并指定下载路径
    text = 'ssfs https://v.douyin.com/cCBrrq/ fsfdd'

    client = Stealer(options={})
    client.dispatch(text).fetch(stream=True, output='1111.mp4')
    client.dispatch(text).parse(header=True)
